package com.zwz.utils;

import java.io.IOException;
import java.io.OutputStream;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.util.concurrent.*;

public class TcpClient {
    // 连接池（线程安全的Map）
    private static final ConcurrentMap<String, Socket> connectionPool = new ConcurrentHashMap<>();
    private static final ExecutorService executor = Executors.newCachedThreadPool();
    private static final int CONNECTION_TIMEOUT = 3000;
    private static final int SOCKET_TIMEOUT = 5000;

    /**
     * 发送数据（复用连接）
     * @param ip 目标IP
     * @param port 目标端口
     * @param message 消息内容
     */
    public static void sendAsync(String ip, int port, String message) {
        if (!message.endsWith("\r\n")) {
            message = message + "\r\n";
        }
        String finalMessage = message;
        executor.submit(() -> {
            String key = ip + ":" + port;
            Socket socket = null;

            try {
                // 尝试从连接池获取现有连接
                socket = connectionPool.get(key);

                // 如果连接不存在或已关闭，创建新连接
                if (socket == null || socket.isClosed() || !socket.isConnected()) {
                    socket = new Socket();
                    socket.setSoTimeout(SOCKET_TIMEOUT);
                    socket.connect(new InetSocketAddress(ip, port), CONNECTION_TIMEOUT);
                    connectionPool.put(key, socket);
                    System.out.println("创建新连接: " + key);
                }

                // 发送数据
                OutputStream out = socket.getOutputStream();
                out.write(finalMessage.getBytes());
                out.flush();
                System.out.println("数据已发送至 " + key);

            } catch (IOException e) {
                System.err.println("发送数据到 " + key + " 失败: " + e.getMessage());
                // 发生异常时移除无效连接
                if (socket != null) {
                    try {
                        socket.close();
                    } catch (IOException ex) {
                        ex.printStackTrace();
                    }
                    connectionPool.remove(key);
                }
                // 可以添加重试逻辑
            } finally {
                // 如果是短连接模式，使用后关闭
                // if (!isNewConnection && socket != null) {
                //     try {
                //         socket.close();
                //     } catch (IOException e) {
                //         e.printStackTrace();
                //     }
                //     connectionPool.remove(key);
                // }
            }
        });
    }

    /**
     * 关闭指定连接
     * @param ip IP地址
     * @param port 端口号
     */
    public static void closeConnection(String ip, int port) {
        String key = ip + ":" + port;
        Socket socket = connectionPool.remove(key);
        if (socket != null) {
            try {
                socket.close();
                System.out.println("已关闭连接: " + key);
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    /**
     * 关闭所有连接和线程池
     */
    public static void shutdown() {
        connectionPool.forEach((key, socket) -> {
            try {
                socket.close();
                System.out.println("已关闭连接: " + key);
            } catch (IOException e) {
                e.printStackTrace();
            }
        });
        connectionPool.clear();
        executor.shutdown();
    }
}